package com.xiaowu.house.house.service.mq;


import com.xiaowu.house.appuser.domain.dto.AppUserDTO;
import com.xiaowu.house.house.service.IHouseService;
import com.xiaowu.house.user.config.RabbitConfig;
import com.xiaowu.house.user.domain.entity.AppUser;
import com.xiaowu.house.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@RabbitListener(bindings = {
        @QueueBinding(
                value = @Queue(),
                exchange = @Exchange(value = RabbitConfig.EXCHANGE_NAME, type = ExchangeTypes.FANOUT)
        )
})
public class EditAppUserMessageReceiver {

    @Autowired
    private IHouseService houseService;

    @RabbitHandler
    public void process(AppUserDTO appUserDTO) {
        if (null == appUserDTO || null == appUserDTO.getUserId()) {
            log.error("MQ接收到的用户消息为空或用户ID为空");
            return;
        }

        log.info("MQ成功接收到消息，message:{}", JsonUtil.obj2String(appUserDTO));

        try {
            //获取用户下的房源ID列表
            List<Long> houseIds = houseService.listByUserId(appUserDTO.getUserId());

            //更新用户下的房源列表的缓存
            for (Long houseId : houseIds) {
                houseService.cacheHouse(houseId);
            }

        } catch (Exception e) {
            log.error("处理用户更新时，更新房源缓存异常, appUserDTO:{}", appUserDTO, e);
        }
    }

}
